<template>
    <div class="sub-menu-wrap">
        <div class="sub-menu-box">
            <el-button icon="el-icon-chat-dot-round" class="btn-create" round @click="add_msg_group"
                :disabled="isLocked" :loading="isButtonLoading">
                新建对话
            </el-button>
            <el-menu :default-active="form.id.toString()" class="sub-menu">
                <el-menu-item v-for="item in group_list" :index="item.id.toString()" :key="item.id"
                    class="text-ellipsis" :class="{ 'is-active': form.id === item.id, 'is-locked': isLocked }"
                    @click="show(item)">
                    <template slot="title">
                        <i class="el-icon-chat-dot-round" style="font-size:14px"></i>
                        <span>{{ item.name }}</span>
                    </template>
                    <el-dropdown trigger="click" class="btn-edit" @command="handleCommand($event, item)">
                        <span class="el-dropdown-link">
                            <i class="el-icon-more"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="edit" icon="el-icon-edit">编辑</el-dropdown-item>
                            <el-dropdown-item command="del" icon="el-icon-delete">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-menu-item>
            </el-menu>

            <el-dialog title="编辑对话" :visible.sync="editFormVisible" @close="cancelEdit">
                <el-form :model="form">
                    <el-form-item label="对话名称" label-width="30">
                        <el-input v-model="form.name" autocomplete="off" ref="editInput"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelEdit">取消</el-button>
                    <el-button type="primary" @click="edit_msg_group">确定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { get_msg, add_group, edit_group, del_group } from "@/apis/group";

export default {
    name: "MessageList",
    data() {
        return {
            app_id: '',
            group_list: [],
            messages: [],
            dialogFormVisible: false,
            editFormVisible: false,
            form: {
                id: '',
                name: "",
                msg: ""
            },
            originalName: "", // 保存原始名称
            isSubmitting: false, // 添加一个标志位来跟踪是否正在提交
            isLocked: false, // 添加一个标志位来跟踪是否锁定
            isButtonLoading: false // 添加一个标志位来跟踪按钮的加载状态
        }
    },

    async created() {
        this.bus.$on("message_groups", groups => {
            this.app_id = localStorage.getItem('app_id');
            this.group_list = groups;
            if (groups.length === 0) {
                this.add_msg_group();
            } else {
                this.show(groups[0]);
            }
        });
    },

    methods: {
        async add_msg_group() {
            if (this.isLocked) {
                this.$message({
                    type: 'warning',
                    message: '当前对话正在响应，请稍后再试'
                });
                return;
            }

            this.isButtonLoading = true; // 设置按钮为加载状态

            this.reset();
            this.bus.$emit("toList", []);
            this.app_id = localStorage.getItem('app_id');
            let newGroupName = "新对话" + (this.group_list.length + 1);
            try {
                const ret = await add_group({ app: this.app_id, name: newGroupName });
                console.log(ret);
                ret['msg'] = "";
                this.group_list.push(ret);
                this.show(ret, true); // 显示新对话并传递 true 表示需要转移焦点
            } catch (error) {
                console.error("新建对话失败", error);
            } finally {
                this.isButtonLoading = false; // 恢复按钮为初始状态
            }
        },

        async show(form, focus = false) {
            if (this.isSubmitting || this.isLocked) {
                this.$message({
                    type: 'warning',
                    message: '当前对话正在响应，请稍后再试'
                });
                return;
            }

            // 更新当前激活的对话
            this.form = form;
            let group = this.group_list.find(item => item.id === form.id);
            localStorage.setItem('group', JSON.stringify(group));
            this.bus.$emit("group", group);

            // 获取新的对话消息
            try {
                const data = await get_msg(form.id);
                let messages = JSON.parse(data['msg']);
                console.log(messages);

                localStorage.setItem('message', JSON.stringify(messages));
                this.bus.$emit("toList", messages);

                // 如果需要转移焦点
                if (focus) {
                    this.$nextTick(() => {
                        const inputField = this.$refs.editInput;
                        if (inputField) {
                            inputField.focus();
                        }
                    });
                }
            } catch (error) {
                console.error("获取消息失败", error);
            }
        },

        async edit_msg_group() {
            if (this.isLocked) return; // 锁定状态下不允许编辑对话

            try {
                const ret = await edit_group(this.form);
                const groupIndex = this.group_list.findIndex(item => item.id === this.form.id);
                if (groupIndex !== -1) {
                    // 使用 Vue.set 确保响应性更新
                    this.$set(this.group_list, groupIndex, { ...this.group_list[groupIndex], name: this.form.name });
                }
                this.editFormVisible = false;
                localStorage.setItem('groups', JSON.stringify(this.group_list));
            } catch (error) {
                console.error("编辑对话失败", error);
            }
        },

        async del_msg_group() {
            if (this.isLocked) return; // 锁定状态下不允许删除对话

            try {
                await this.$confirm('此操作将永久删除该对话, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                let id = this.form.id;
                this.bus.$emit("toList", []);

                // 删除对话
                await del_group(id);

                // 从 group_list 中删除对话
                const groupIndex = this.group_list.findIndex(item => item.id === id);
                if (groupIndex !== -1) {
                    this.group_list.splice(groupIndex, 1);
                }

                // 更新本地存储中的对话列表
                localStorage.setItem('groups', JSON.stringify(this.group_list));

                // 删除本地存储中的当前对话相关数据
                localStorage.removeItem('group');
                localStorage.removeItem('message');

                // 如果还有其他对话，显示第一个对话，否则创建一个新的对话
                if (this.group_list.length > 0) {
                    this.show(this.group_list[0]);
                } else {
                    this.add_msg_group();
                }
            } catch (error) {
                console.error("删除对话失败", error);
            }
        },

        reset() {
            localStorage.setItem('message', "[]");
            this.bus.$emit("toList", []);
        },

        handleCommand(type, form) {
            if (this.isLocked) {
                this.$message({
                    type: 'warning',
                    message: '当前对话正在响应，请稍后再试'
                });
                return; // 锁定状态下不允许操作
            }
            if (type === 'edit') {
                this.form = form;
                this.originalName = form.name; // 保存原始名称
                this.editFormVisible = true;
            } else {
                this.del_msg_group();
            }
        },

        cancelEdit() {
            this.form.name = this.originalName; // 恢复原始名称
            this.editFormVisible = false;
        },

        // 新增方法，处理应用列表点击事件
        showApp(app) {
            if (this.isLocked) {
                this.$message({
                    type: 'warning',
                    message: '当前对话正在响应，请稍后再试'
                });
                return;
            }

            // 更新当前激活的应用
            this.app_id = app.id;
            localStorage.setItem('app_id', app.id);
            this.bus.$emit("app", app);

            // 获取新的应用相关数据
            // 假设有类似 get_app_data 的方法
            get_app_data(app.id).then(data => {
                // 处理应用数据
                console.log(data);
            });
        }
    },

    mounted() {
        this.bus.$on('lod', (status) => {
            this.isSubmitting = status;
        });
        this.bus.$on('lockLists', (status) => {
            this.isLocked = status;
        });
    }
}
</script>




<style scoped>
.is-locked {
    pointer-events: none;
    opacity: 0.6;
}

.sub-menu-wrap {
    height: 100%;
}

.sub-menu-box {
    position: relative;
    height: 100%;
    border-right: 1px solid #DFE2EA;
    padding: 16px;
    box-sizing: border-box;
}

.btn-create {
    width: 100%;
    margin: 16px 0;
}

.sub-menu {
    border-right: 0 none;
}

.btn-edit {
    float: right;
    line-height: 45px;
    display: block;
    display: none;
}

.el-menu-item,
.el-submenu__title {
    line-height: 45px;
    height: 45px;
}

.el-menu-item:focus,
.el-menu-item:hover {
    border-radius: 10px;
}

.el-menu-item:focus .btn-edit,
.el-menu-item:hover .btn-edit {
    display: block;
}

.el-menu-item.is-active {
    background-color: #ecf5ff;
    border-radius: 10px;
}

.el-menu-item.is-active .btn-edit {
    display: block;
}

.text-ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}
</style>
